<?php declare(strict_types=1);

namespace App\Api\V2\Controller\User;

use App\Api\Controllers\BaseController;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\StoreWaysDesc;
use App\Models\User;
use App\Models\UserRate;
use App\Services\PassVerifyService;
use App\Services\PrintSqlService;
use App\Services\Rate\UserRateService;
use App\Traits\ResponseTrait;
use App\Util\ListUtil;
use App\Util\SqlWhenUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserController extends BaseController
{

    use ResponseTrait;

    //成本费率列表
    public function user_ways_allBAK(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = (int)$request->get('user_id');

            // if($user->user_id !== 1){
            //     return json_encode([
            //         'status' => 2,
            //         'message' => "待开发"
            //     ]);
            // }
            $data = [];
            $service = new UserRateService();
            $cost = $service->costRateList((int)$user->user_id, $user_id, ["weixin", "alipay", "unionpay"]);
            //
            $costAppletBest = $service->costRateList((int)$user->user_id, $user_id, ["Bestpay", "applet"]);
            $data = array_merge($data, $cost, $costAppletBest);
            return json_encode([
                'status' => 1,
                'data' => $data
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => '-1',
                'message' => $exception->getMessage() . ' | ' . $exception->getFile() . ' | ' . $exception->getLine()
            ]);
        }
    }

    public function user_ways_all(Request $request)
    {
        try {
            $user = $this->parseToken();

            $user_id = (int)$request->get('user_id');

            $where = [
                "company" => $request->get("company", "")
            ];
            $service = new UserRateService();

            $data = $service->userRateList((int)$user->user_id, $user_id, $where);

            return $this->successResponse("ok", [
                "data" => $data,
            ]);
        } catch (\Exception $exception) {
            return $this->errorResponse($exception->getMessage() . ' | ' . $exception->getFile() . ' | ' . $exception->getLine());
        }
    }

    //编辑成本费率
    public function edit_user_rate(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->post('user_id');
            $data = $request->all();
            $validator = Validator::make(
                $data,
                [
                    "company" => ["required"],
//                    "rate" => ["required", "numeric", "between:0,1"],
                    "server_rate" => ["required", "numeric", "between:0,1"],
                    "yu_rate" => ["required", "numeric", "between:0,1"],
                    "era_rate" => ["required", "numeric", "between:0,1"],
                    "rate_a" => ["nullable", "numeric", "between:0,1"],
                    "rate_c" => ["nullable", "numeric", "between:0,1"],
                    "rate_e" => ["nullable", "numeric", "between:0,1"],
                    "rate_f" => ["nullable", "numeric", "between:0,1"],
                    "rate_f_top" => ["nullable", "numeric", "min:0"],
                    "rate_bestpay" => ["nullable", "numeric", "between:0,1"],  //翼支付
                    "rate_wx" => ["nullable", "numeric", "between:0,1"],  //翼支付,
                    "rate_alipay" => ["nullable", "numeric", "between:0,1"],  //翼支付,
                ],
                [],
                [
//                    "rate" => "基础费率",
                    "rate_a" => "云闪付0-1000费率",
                    "rate_c" => "云闪付1000以上费率",
                    "rate_e" => "刷卡信用卡费率",
                    "rate_f" => "刷卡储蓄卡费率",
                    "rate_f_top" => "刷卡储蓄卡封顶手续费",
                    "company" => "公司名称",
                    "server_rate" => "服务费费率",
                    "yu_rate" => "预充费率",
                    "era_rate" => "代扣费率",
                    "rate_bestpay" => "翼支付",  //翼支付
                    "rate_wx" => "微信费率",  //翼支付,
                    "rate_alipay" => "支付宝费率",  //翼支付,
                ]
            );
            if ($validator->fails()) {
                return $this->errorResponse($validator->errors()->first());
            }
            //需要判断 翼支付【单独更新】 |  微信-支付宝-银联
            $astore_ways_desc = StoreWaysDesc::query()
                ->select('company')
                ->where("company", $data["company"])
                ->get()->toArray();
            if (empty($astore_ways_desc)) {
                return $this->errorResponse("通道基础数据不存在");
            }
            //开始业务逻辑和编辑数据
            $edit_user = User::query()->where('id', $user_id)->first();
            if (!$edit_user) {
                return $this->errorResponse("代理商不存在");
            } else if ($user_id == $user->user_id && $user->level != 0) {
                return $this->errorResponse("不能设置自己的费率请联系上级");
            }
            //开始获取上级费率，并且确保修改的费率大于上级费率
            //"Bestpay", "applet"
            //Bestpay "weixin", "alipay", "unionpay"
            //被设置者是平台以下的账户不能大于上级的成本
            if ($edit_user->level > 0 && $edit_user->pid > 0) {

                $user_pid_rate = UserRate::query()
                    ->select([
                        "user_rates.company", "user_rates.rate", "user_rates.rate_a", "user_rates.rate_c", "user_rates.rate_e", "user_rates.rate_f",
                        "user_rates.rate_f_top",
                        "user_rates.server_rate",
                        "user_rates.era_rate",
                        "user_rates.yu_rate",
                        "store_ways_desc.ways_desc",
                        "store_ways_desc.ways_source",
                    ])
                    ->leftJoin("store_ways_desc", "user_rates.ways_type", "=", "store_ways_desc.ways_type")
                    ->where("user_rates.user_id", $edit_user->pid)
                    ->where("user_rates.company", $data["company"])
                    ->where("user_rates.status", 1)
                    ->get()->toArray();
                if (empty($user_pid_rate)) {
                    return $this->errorResponse("上级代理商未设置费率");
                }
                $commonRate = $user_pid_rate[0];
                $user_pid_rate = array_combine(array_column($user_pid_rate, "ways_source"), $user_pid_rate);
                //微信-支付宝-费率
//                "rate_bestpay" => "翼支付",  //翼支付
//                    "rate_wx" => "微信费率",  //翼支付,
//                    "rate_alipay" => "支付宝费率",  //翼支付,
                if (!empty($user_pid_rate["weixin"]) && $data["rate_wx"] < $user_pid_rate["weixin"]["rate"]) {
                    return $this->errorResponse("微信费率不能低于上级代理商的费率");
                }

                if (!empty($user_pid_rate["alipay"]) && $data["rate_alipay"] < $user_pid_rate["alipay"]["rate"]) {
                    return $this->errorResponse("支付宝费率不能低于上级代理商的费率");
                }

                if (isset($user_pid_rate["Bestpay"]) && $data["rate_bestpay"] < $user_pid_rate["Bestpay"]["rate"]) {
                    return $this->errorResponse("翼支付费率不能低于上级代理商的费率");
                }
                if (isset($user_pid_rate["unionpay"]) && $data["rate_a"] < $user_pid_rate["unionpay"]["rate_a"]) {
                    return $this->errorResponse("云闪付费率不能低于上级代理商的费率");
                }
                if (isset($user_pid_rate["unionpay"]) && $data["rate_c"] < $user_pid_rate["unionpay"]["rate_c"]) {
                    return $this->errorResponse("云闪付大于1000费率不能低于上级代理商的费率");
                }

                if (isset($user_pid_rate["unionpay"]) && $data["rate_c"] < $user_pid_rate["unionpay"]["rate_c"]) {
                    return $this->errorResponse("云闪付大于1000费率不能低于上级代理商的费率");
                }

                if (isset($user_pid_rate["unionpay"]) && $data["rate_e"] < $user_pid_rate["unionpay"]["rate_e"]) {
                    return $this->errorResponse("云闪付信用卡刷卡费率不能低于上级代理商的费率");
                }

                if (isset($user_pid_rate["unionpay"]) && $data["rate_f"] < $user_pid_rate["unionpay"]["rate_f"]) {
                    return $this->errorResponse("云闪付储蓄卡刷卡费率不能低于上级代理商的费率");
                }

                if ($data["server_rate"] < $commonRate["server_rate"]) {
                    return $this->errorResponse("服务费率不能低于上级代理商的费率");
                }
                if ($data["yu_rate"] < $commonRate["yu_rate"]) {
                    return $this->errorResponse("预充费率不能低于上级代理商的费率");
                }
                if ($data["era_rate"] < $commonRate["era_rate"]) {
                    return $this->errorResponse("代扣费率不能低于上级代理商的费率");
                }
            }
            $data = [
                'user_id' => $user_id,
                'server_rate' => $data["server_rate"],
                'yu_rate' => $data["yu_rate"],
                'era_rate' => $data["era_rate"],
                'company' => $data["company"],
//                'rate' => $data["rate"],
                "rate_a" => $data["rate_a"],
                "rate_c" => $data["rate_c"],
                "rate_e" => $data["rate_e"],
                "rate_f" => $data["rate_f"],
                "rate_f_top" => $data["rate_f_top"],

                "rate_wx" => $data["rate_wx"],
                "rate_bestpay" => $data["rate_bestpay"] ?? 0,
                "rate_alipay" => $data["rate_alipay"],
            ];
//

            DB::beginTransaction();
            try {
                //批量处理数据更新
                $ups = StoreWaysDesc::query()->where("company", $data["company"])
                    ->get()->toArray();
                $waysTypeArr = array_column($ups, "ways_type");
                $waysAll = UserRate::query()->where("user_id", $data["user_id"])->whereIn("ways_type", $waysTypeArr)->get()->toArray();
                $waysAll = array_combine(array_column($waysAll, "ways_type"), $waysAll);
                $updated = $created = [];
                foreach ($ups as $up) {
                    $tmp = [
                        'user_id' => $user_id,
                        'server_rate' => $data["server_rate"],
                        'yu_rate' => $data["yu_rate"],
                        'era_rate' => $data["era_rate"],
                        'company' => $data["company"],
                        "rate_a" => $data["rate_a"],
                        "rate_c" => $data["rate_c"],
                        "rate_e" => $data["rate_e"],
                        "rate_f" => $data["rate_f"],
                        "rate_f_top" => $data["rate_f_top"],
                        "ways_type" => $up["ways_type"]
                    ];

                    //Bestpay "weixin", "alipay", "unionpay"
//                    "rate_bestpay" => "翼支付",  //翼支付
//                    "rate_wx" => "微信费率",  //翼支付,
//                    "rate_alipay" => "支付宝费率",  //翼支付,
                    if ($up["ways_source"] == "Bestpay") {
                        $tmp["rate"] = $data["rate_bestpay"];
                    } else if ($up["ways_source"] == "weixin") {
                        $tmp["rate"] = $data["rate_wx"];
                    } else if ($up["ways_source"] == "alipay") {
                        $tmp["rate"] = $data["rate_alipay"];
                    } else if ($up["ways_source"] == "unionpay") {
                        $tmp["rate"] = $data["rate_a"];
                    } else if($up["ways_source"] == "jd"){
                        $tmp["rate"] = $data["rate_wx"];
                    } else if($up["ways_source"] == "applet"){
                        $tmp["rate"] = $data["rate_wx"];
                    }
//                    $ways = UserRate::query()->where('user_id', $data['user_id'])->where('ways_type', $up->ways_type)->first();
                    if (!isset($waysAll[$up["ways_type"]])) {

                        $created[] = $tmp;
//                        UserRate::query()->create($data);
                    } else {
                        if ($user->user_id != 1) {
                            throw new \Exception("只有顶级账号才允许修改费率");
                        }
                        $tmp["id"] = $waysAll[$up["ways_type"]]["id"];
                        unset($tmp["user_id"]);
                        $updated[] = $tmp;
//                        UserRate::query()->where("id", $up->id)->update($data);
                    }
                }
                //在这里检查密钥
                if (!empty($updated)) {
                    PassVerifyService::pass($request, $this, function () use ($user_id, $request) {
                        return '修改成本费率: user_id: ' . $user_id . "参数:" . json_encode($request->all());
                    });
                }
                //在这里设置批量操作
                if (!empty($created)) {
                    UserRate::query()->insert($created);
                }
                if (!empty($updated)) {
                    $util = new SqlWhenUtil();
                    list($whereValue, $updatedRaw) = $util->caseSql($updated, "id");
                    UserRate::query()->whereIn("id", $whereValue)->update($updatedRaw);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->errorResponse($e->getMessage());
            }
            return $this->successResponse("ok");
        } catch (\Exception $exception) {
            return $this->errorResponse($exception->getMessage());
        }
    }


    public function userList(Request $request)
    {
        $user_id = $request->get("user_id");
        $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
        $systemUserArray = ListUtil::createListsNode($systemUserArray);
        $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user_id]);
        $userCollection = ListUtil::listsNodeToArray([$userCollection]);
        $userCollectionIds = array_column($userCollection, "id");
        return implode(",", $userCollectionIds);
    }

}
